const db = require("./database.js")

async function selectAddrListByUserId(user_id) {
  return new Promise((resolve, reject) => {
    db.all("select * from addr where user_id = ?", [user_id], (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows)
      }
    });
  })
}

async function insertAddr(addr) {
  return new Promise((resolve, reject) => {
    db.run('insert into addr(user_id, name, address, phone_number, is_default) values (?,?,?,?,?)', [addr.user_id, addr.name, addr.address, addr.phone_number, addr.is_default], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    });
  });
}

async function deleteAddr(addr_id) {
  return new Promise((resolve, reject) => {
    db.run('delete from addr where addr_id = ?', [addr_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    });
  });
}

async function updateAddr(addr) {
  return new Promise((resolve, reject) => {
    db.run('update addr set name = ?, address = ?, phone_number = ?, is_default = ? where addr_id = ?', [addr.name, addr.address, addr.phone_number, addr.is_default, addr.addr_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    })
  })
}

async function updateAddrDefault(addr) {
  return new Promise((resolve, reject) => {
    db.run('update addr set is_default = ? where addr_id = ?', [addr.is_default, addr.addr_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    })
  })
}

async function selectAddrByAddrId(addr_id) {
  return new Promise((resolve, reject) => {
    db.get('select * from addr where addr_id = ?', [addr_id], (err, row) => {
      if (err) {
        reject(err);
      } else {
        resolve(row)
      }
    })
  })
}


module.exports = {
  selectAddrListByUserId,
  insertAddr,
  deleteAddr,
  updateAddr,
  updateAddrDefault,
  selectAddrByAddrId
}
